package my.senix.sc.servlet;

import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;

/**
 * Created by lhs on 2018/11/26.
 */
@Slf4j
public class MyServlet extends HttpServlet {

    private String addr;

    @Override
    public void init() throws ServletException {
        ServletConfig servletConfig = getServletConfig();

        this.addr = servletConfig.getInitParameter("addr");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        log.info("进入rui:{}", req.getRequestURL());

        //http header 只能是ASCII码，所以只能url编码
        resp.addHeader("name", URLEncoder.encode("打发点法法","utf-8"));
        write(resp, "{\"stauts\":\"success\",\"addr\":\"" + addr + "\"}");

    }

    private void write(HttpServletResponse servletResponse, String body) {

        byte[] bytes = body.getBytes(Charset.forName("UTF-8"));
        servletResponse.setBufferSize(1024 * 50);
        servletResponse.setContentType("application/json;charset=utf-8");
        servletResponse.setContentLength(bytes.length);

        try {
            ServletOutputStream outputStream = servletResponse.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
        } catch (IOException e) {
            log.error("writeAndFlush失败，响应body:{},info:{}", body, Throwables.getStackTraceAsString(e));
        }
    }


}
